import os
import time
from dataflare import Client, DataFlareError

def main():
    # Get API URL and key from environment variables
    api_url = os.environ.get("DATAFLARE_API_URL", "http://localhost:8080")
    api_key = os.environ.get("DATAFLARE_API_KEY", "")

    # Create client
    client = Client(
        base_url=api_url,
        api_key=api_key,
        timeout=30.0,
    )

    try:
        # Create workflow
        workflow = client.create_workflow(
            name="example-workflow",
            description="Example workflow",
            definition="""
version: "1.0"
name: "example-workflow"
description: "Example workflow"
config:
  mode: "stream"
  execution:
    engine: "actor"
    parallelism: 1
  state:
    backend: "memory"
schemas:
  record:
    fields:
      id:
        type: "string"
        required: true
      value:
        type: "number"
        description: "Value"
sources:
  memory_source:
    type: "memory"
    schema: "record"
    config:
      data: [
        {"id": "1", "value": 10},
        {"id": "2", "value": 20},
        {"id": "3", "value": 30}
      ]
    description: "In-memory data source"
sinks:
  console_sink:
    type: "console"
    schema: "record"
    config:
      format: "json"
    description: "Console output sink"
nodes:
  process:
    type: "transform"
    description: "Process input records"
    inputs:
      default:
        schema: "record"
    outputs:
      default:
        schema: "record"
    transform:
      language: "javascript"
      code: |
        function process(record) {
          return {
            id: record.id,
            value: record.value * 2
          };
        }
edges:
  - from:
      source: "memory_source"
    to:
      node: "process"
      input: "default"
  - from:
      node: "process"
      output: "default"
    to:
      sink: "console_sink"
""",
        )

        print(f"Created workflow: {workflow.id}")

        # Run workflow
        run = client.run_workflow(
            workflow_id=workflow.id,
            parameters={"param1": "value1"},
        )

        print(f"Started workflow run: {run.id}")

        # Wait for workflow to complete
        try:
            run = client.wait_for_workflow_run(
                workflow_id=workflow.id,
                run_id=run.id,
                timeout=60.0,
                poll_interval=1.0,
            )

            print(f"Workflow run completed with status: {run.status}")
            if run.error:
                print(f"Error: {run.error}")
        except TimeoutError:
            print("Workflow run timed out")
            # Cancel the run
            client.cancel_workflow_run(workflow.id, run.id)
            print(f"Cancelled workflow run: {run.id}")

        # List workflow runs
        result = client.list_workflow_runs(
            workflow_id=workflow.id,
            limit=10,
        )

        print("Workflow runs:")
        for run in result["runs"]:
            print(f"- {run.id}: {run.status}")

        # Delete workflow
        client.delete_workflow(workflow.id)
        print(f"Deleted workflow: {workflow.id}")

    except DataFlareError as e:
        print(f"API error: {e.code} - {e.message}")
    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    main()
